export interface ErrorReport {
  type: 'javascript' | 'promise' | 'network' | 'plugin'
  message: string
  stack?: string
  url?: string
  timestamp: string
  userAgent: string
  userId?: string
}

class ErrorHandler {
  private errorQueue: ErrorReport[] = []
  private isOnline = navigator.onLine

  constructor() {
    this.setupGlobalHandlers()
    this.setupNetworkHandlers()
  }

  private setupGlobalHandlers() {
    // 捕获 JavaScript 错误
    window.addEventListener('error', (event) => {
      this.reportError({
        type: 'javascript',
        message: event.message,
        stack: event.error?.stack,
        url: event.filename,
        timestamp: new Date().toISOString(),
        userAgent: navigator.userAgent
      })
    })

    // 捕获 Promise 拒绝
    window.addEventListener('unhandledrejection', (event) => {
      this.reportError({
        type: 'promise',
        message: event.reason?.message || 'Unhandled Promise Rejection',
        stack: event.reason?.stack,
        timestamp: new Date().toISOString(),
        userAgent: navigator.userAgent
      })
    })
  }

  private setupNetworkHandlers() {
    // 监听网络状态
    window.addEventListener('online', () => {
      this.isOnline = true
      this.flushErrorQueue()
    })

    window.addEventListener('offline', () => {
      this.isOnline = false
    })
  }

  reportError(error: ErrorReport) {
    if (this.isOnline) {
      this.sendError(error)
    } else {
      this.errorQueue.push(error)
    }
  }

  private async sendError(error: ErrorReport) {
    try {
      await fetch('/api/errors', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(error)
      })
    } catch (e) {
      // 如果发送失败，加入队列
      this.errorQueue.push(error)
    }
  }

  private flushErrorQueue() {
    while (this.errorQueue.length > 0) {
      const error = this.errorQueue.shift()
      if (error) {
        this.sendError(error)
      }
    }
  }
}

export const errorHandler = new ErrorHandler()
